package com.ali.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * NIO
 */
public class NIOMain {
    private static final Set<SocketChannel> socketChannels = new HashSet<>();

    public static void main(String[] args) {
        try {
            //构建监听服务
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //设置监听服务为非阻塞状态
            serverSocketChannel.configureBlocking(false);
            //绑定监听端口
            serverSocketChannel.bind(new InetSocketAddress(8080));

            while (true) {
                //获取客户端连接
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel != null) {
                    System.out.println("接收客户端连接");
                    //设置客户端连接为非阻塞状态
                    socketChannel.configureBlocking(false);
                    //保存客户端连接
                    socketChannels.add(socketChannel);
                }
                handle();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理客户端连接
     */
    private static void handle() {
        try {
            //构建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1);
            int length;

            Iterator<SocketChannel> iterator = socketChannels.iterator();
            while (iterator.hasNext()) {
                SocketChannel socketChannel = iterator.next();
                //写入内容至缓冲区
                length = socketChannel.read(byteBuffer);
                if (length > 0) {
                    System.out.println("接收内容：" + new String(byteBuffer.array(), 0, length));
                    //清理缓冲区
                    byteBuffer.clear();
                } else if (length == -1) {
                    System.out.println("客户端断开连接");
                    //移除客户端连接
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
